import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../../base/imageres.dart';
import '../../base/beans/jcring_bean.dart';
import '../../base/lang.dart';
import '../../base/log.dart';
import '../../base/stringres.dart';
import '../../base/theme.dart';
import '../../views/horizontal_line.dart';
import '../../views/jsw_base_view.dart';

///女性健康下面的生理周期历史
class CycleHistoryPage extends StatefulWidget {
  Map<String, int> periodDataMap;
  final int menstrualTime;
  final int cycleValue;
  final int periodValue;

  CycleHistoryPage(
      {super.key,
      required this.periodDataMap,
      required this.menstrualTime,
      required this.cycleValue,
      required this.periodValue});

  @override
  State<StatefulWidget> createState() {
    return _CycleHistoryPageState();
  }
}

class _CycleHistoryPageState extends State<CycleHistoryPage> {
  static const _tag = '[page_cycle_history.dart][_CycleHistoryPageState]';

  ///历史记录列表
  List<History> _historyList = [];

  ///最近一次月经的DateTime
  DateTime _lastMenstrualDateTime = DateTime.now();

  ///月经时长
  int _lastMenstrualLength = 0;

  ///周期时长
  int _lastCycleLength = 0;

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: SystemUiOverlay.values);
    if (widget.periodDataMap.isNotEmpty) {
      List<DateTime> periodDataList = [];
      List<DateTime> periodEndDataList = [];
      widget.periodDataMap.forEach((key, value) {
        if (value == 6) {
          DateTime dateTime = DateTime.parse(key);
          periodDataList.add(dateTime);
          DartLog.i(_tag, "遍历本地周期历史记录月经开始: dateTime${DateFormat("yyyy-MM-dd").format(dateTime)} ");
        }
        if (value == 7) {
          DateTime dateTime = DateTime.parse(key);
          periodEndDataList.add(dateTime);
          DartLog.i(_tag, "遍历本地周期历史记录月经结束: dateTime${DateFormat("yyyy-MM-dd").format(dateTime)} ");
        }
      });
      DateTime startDate = DateTime.fromMillisecondsSinceEpoch(widget.menstrualTime);
      DateTime endDate = startDate.add(Duration(days: widget.cycleValue));
      periodDataList.add(startDate);
      periodEndDataList.add(endDate);
      periodDataList.sort();
      periodEndDataList.sort();
      _lastMenstrualDateTime = periodDataList[periodDataList.length - 1];
      _lastMenstrualLength = _calculateDaysDifference(_lastMenstrualDateTime, DateTime.now());
      _lastCycleLength = _calculateDaysDifference(_lastMenstrualDateTime, DateTime.now());
      if(_lastMenstrualLength >= widget.periodValue){
        _lastMenstrualLength = widget.periodValue;
      }

      DartLog.i(_tag, "periodDataList: ${periodDataList.toString()}");
      for (int i = 0; i < periodDataList.length - 1; i++) {
        DateTime startDate = periodDataList[i];
        DateTime periodEndDate = periodEndDataList[i];
        DateTime endDate = periodDataList[i + 1].subtract(const Duration(days: 1));
        DartLog.i(_tag, "本地周期历史记录: startDate${DateFormat("yyyy-MM-dd").format(startDate)} endDate:${DateFormat("yyyy-MM-dd").format(endDate)}");
        bool isShowYear = true;
        if (DateTime.now().year == startDate.year && DateTime.now().year == endDate.year) {
          isShowYear = false;
        }
        _historyList.add(History(
            S.isCN() ? DateFormat(isShowYear ? "yyyy年MM月dd日" : "MM月dd日").format(startDate) : stringFromDate(startDate, isShowYear ? "MMM dd, yyyy" : "MMM dd"),
            S.isCN() ? DateFormat(isShowYear ? "yyyy年MM月dd日" : "MM月dd日").format(endDate) : stringFromDate(endDate, isShowYear ? "MMM dd, yyyy" : "MMM dd"),
            _calculateDaysDifference(startDate, endDate),
            _calculateDaysDifference(startDate, periodEndDate)));
      }
    } else {
      _initHistoryList(widget.menstrualTime);
    }

    DartLog.i(_tag, "最近一次的月经开始时间: _lastMenstrualDateTime${DateFormat("yyyy-MM-dd").format(_lastMenstrualDateTime)} $_lastMenstrualLength $_lastCycleLength");
  }

  void _initHistoryList(int startTime) {
    int currentTime = startTime;
    while (true) {
      DateTime startDate = DateTime.fromMillisecondsSinceEpoch(currentTime);
      DateTime endDate = startDate.add(Duration(days: widget.cycleValue));
      if (endDate.millisecondsSinceEpoch > DateTime.now().millisecondsSinceEpoch) {
        _lastMenstrualDateTime = startDate;
        _lastMenstrualLength = _calculateDaysDifference(_lastMenstrualDateTime, DateTime.now());
        _lastCycleLength = _calculateDaysDifference(_lastMenstrualDateTime, DateTime.now());
        if(_lastMenstrualLength >= widget.periodValue){
          _lastMenstrualLength = widget.periodValue;
        }
        break;
      }
      DartLog.i(_tag, '_initHistoryList startDate: ${DateFormat("yyyy-MM-dd").format(startDate)} endDate: ${DateFormat("yyyy-MM-dd").format(endDate)}');
      bool isShowYear = true;
      if (DateTime.now().year == startDate.year && DateTime.now().year == endDate.year) {
        isShowYear = false;
      }
      _historyList.add(History(
          S.isCN() ? DateFormat(isShowYear ? "yyyy年MM月dd日" : "MM月dd日").format(startDate) : stringFromDate(startDate, isShowYear ? "MMM dd, yyyy" : "MMM dd"),
          S.isCN() ? DateFormat(isShowYear ? "yyyy年MM月dd日" : "MM月dd日").format(endDate.subtract(const Duration(days: 1))) : stringFromDate(endDate.subtract(const Duration(days: 1)), isShowYear ? "MMM dd, yyyy" : "MMM dd"),
          widget.cycleValue,
          widget.periodValue));
      currentTime = endDate.millisecondsSinceEpoch;
    }
  }

  /// 计算两个 DateTime 对象相差的天数
  int _calculateDaysDifference(DateTime startDate, DateTime endDate) {
    return (startDate.difference(endDate).inDays).abs() + 1;
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final eachPartWidth = (screenWidth - 100.0) / 45;
    return Stack(
      children: [
        Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(ImageRes.bg_health_set),
              fit: BoxFit.cover, // 图片填充方式
            ),
          ),
        ),
        Scaffold(
          backgroundColor: Colors.transparent, // 设置 Scaffold 背景透明
          appBar: AppBar(
            elevation: 0.0,
            backgroundColor: Colors.transparent,
            title: EasyTouch(
              width: double.infinity,
              padding: const EdgeInsets.only(right: 55),
              child: Text(
                StringRes.women_history_title,
                textAlign: TextAlign.center,
                style: ThemeUtil.toolbar,
              ),
            ),
            leading: IconButton(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent,
              hoverColor: Colors.transparent,
              icon: const Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              onPressed: () {
                Get.back();
              },
            ),
          ),
          body: SingleChildScrollView(
            child: Container(
                margin: const EdgeInsets.only(top: 10, left: 15, right: 15,bottom: 50),
                padding: const EdgeInsets.only(top: 24,left: 15, right: 15,bottom: 24,),
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0XFF1B1D20),
                      Color(0XFF141518)
                    ],
                  ),
                  borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    JSWLine(
                      clickable: false,
                      margin: const EdgeInsets.only(bottom: 24),
                      children: [
                        BaseViewItem(
                          weight: 1,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                width: 10,
                                height: 10,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(2.0),
                                  color: const Color(ThemeUtil.primarPredictionValue),
                                ),
                              ),
                              const SizedBox(
                                height: 10.0,
                                width: 4.0,
                              ),
                              Text(
                                StringRes.menstruation_days,
                                textAlign: TextAlign.center,
                                softWrap: true,
                                style: ThemeUtil.p2.copyWith(
                                    fontSize: 14,
                                    color:
                                    const Color(ThemeUtil.primaryWhiteValue50)),
                              ),
                            ],
                          ),
                        ),
                        BaseViewItem(
                          weight: 1,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                width: 10,
                                height: 10,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(2.0),
                                  color: const Color(ThemeUtil.primarPredictionValue).withOpacity(0.2),
                                ),
                              ),
                              const SizedBox(
                                height: 10.0,
                                width: 4.0,
                              ),
                              Text(
                                StringRes.cycle_length,
                                textAlign: TextAlign.center,
                                softWrap: true,
                                style: ThemeUtil.p2.copyWith(
                                    fontSize: 14,
                                    color:
                                    const Color(ThemeUtil.primaryWhiteValue50)),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),

                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [

                        HorizontalLine(dashedHeight: 0.5, color: Colors.white24),

                        Container(
                          margin: const EdgeInsets.only(top: 15, bottom: 10),
                          child: Text(
                            textAlign: TextAlign.center,
                            "${StringRes.current_cycle}: ${S.isCN() ? DateFormat("MM月dd日").format(_lastMenstrualDateTime) : stringFromDate(_lastMenstrualDateTime, "MMM dd")} – ${StringRes.today}",
                            style: ThemeUtil.mp3,
                          ),
                        ),

                        Stack(
                          children: [
                            Container(
                              height: 16,
                              width: eachPartWidth * _lastCycleLength,
                              decoration: BoxDecoration(
                                color: const Color(ThemeUtil.primarPredictionValue).withOpacity(0.2),
                                borderRadius: BorderRadius.circular(90.0),
                              ),
                            ),
                            Container(
                                height: 16,
                                width: eachPartWidth * _lastMenstrualLength,
                                padding: const EdgeInsets.only(right: 4),
                                alignment: Alignment.centerRight,
                                decoration: BoxDecoration(
                                  color: const Color(ThemeUtil.primarPredictionValue),
                                  borderRadius: BorderRadius.circular(90.0),
                                ),
                                child: Text(
                                  "$_lastMenstrualLength",
                                  textAlign: TextAlign.center,
                                  style: ThemeUtil.p2.copyWith(fontSize: 12),
                                )),
                            Container(
                              margin: EdgeInsets.only(left: eachPartWidth * _lastCycleLength),
                              width: 40.0,
                              child: Text(
                                textAlign: TextAlign.center,
                                "$_lastCycleLength",
                                style: ThemeUtil.mp4.copyWith(fontFamily: 'Regular'),
                              ),
                            ),
                          ],
                        )
                      ],
                    ),

                    for(int i = _historyList.length - 1; i >= 0; i--)
                    _geHistoryListWidget(i,eachPartWidth),
                  ],
                )),
          ),
        ),
      ],
    );
  }

  Widget _geHistoryListWidget(int index,double eachPartWidth) {
    return Container(
      margin: const EdgeInsets.only(top: 20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [

          HorizontalLine(dashedHeight: 0.5, color: Colors.white24),

          Container(
            margin: const EdgeInsets.only(top: 15, bottom: 10),
            child: Text(
              textAlign: TextAlign.center,
              "${_historyList[index].startTime} - ${_historyList[index].endTime}",
              style: ThemeUtil.mp3,
            ),
          ),

          Stack(
            children: [
              Container(
                height: 16,
                width: eachPartWidth * _historyList[index].cycle,
                decoration: BoxDecoration(
                  color: const Color(ThemeUtil.primarPredictionValue).withOpacity(0.2),
                  borderRadius: BorderRadius.circular(90.0),
                ),
              ),
              Container(
                  height: 16,
                  width: eachPartWidth * _historyList[index].period,
                  padding: const EdgeInsets.only(right: 4),
                  alignment: Alignment.centerRight,
                  decoration: BoxDecoration(
                    color: const Color(ThemeUtil.primarPredictionValue),
                    borderRadius: BorderRadius.circular(90.0),
                  ),
                  child: Text(
                    "${_historyList[index].period}",
                    textAlign: TextAlign.center,
                    style: ThemeUtil.p2.copyWith(fontSize: 12),
                  )),
              Container(
                margin: EdgeInsets.only(left: eachPartWidth * _historyList[index].cycle),
                width: 40.0,
                child: Text(
                  textAlign: TextAlign.center,
                  "${_historyList[index].cycle}",
                  style: ThemeUtil.mp4.copyWith(fontFamily: 'Regular'),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  String stringFromDate(DateTime date, String strFormat) {
    var dateFormat = DateFormat(strFormat, 'en_US_POSIX');
    return dateFormat.format(date);
  }
}
